import React, { Fragment, useEffect } from 'react';
import { Route, useLocation, useHistory } from 'react-router-dom';
import routerList from '../router';
import LayoutMain from '../components/layout'

const aloneRouter = routerList.filter(i => i.alone)
const businessRouter = routerList.filter(i => !i.alone)

console.log('当前使用的环境是:', process.env.REACT_APP_ENV)

function setTitle(pathname) {
  const route = businessRouter.find(i => i.path === pathname)
  document.title = route ? route.title : '嘻嘻嘻'
}

function App() {
  const { pathname } = useLocation()
  const history = useHistory()

  setTitle(pathname)

  useEffect(() => {
    setTitle(pathname)
  }, [pathname])

  if (pathname !== '/login' && !window.localStorage.getItem('token')) {
    history.push('/login')
  }

  if (pathname === '/') {
    history.push('/navigation')
  }

  if (aloneRouter.some(i => i.path === pathname)) {
    return <Fragment>{aloneRouter.map((i) => <Route key={i.path} exact path={i.path} component={i.component} />)}</Fragment>
  }
  return <LayoutMain businessRouter={businessRouter} />
}

export default App;
